<?php

namespace backend\modules\agent\controllers;

use backend\controllers\BaseController;
use yii;
use yii\helpers\Url;
use common\models\SysBoss;
use yii\data\Pagination;
use common\models\SysUser;
use common\models\Status;
use common\models\SysShop;
use backend\models\OpenapiShop;
use yii\base\Controller;
use yii\base\Object;
use common\models\SysAgent;
/**
 * 老板增删改查 (只允许代理商操作)
 * @author      futao
 * @date        2016-2-1
 * @version     2.0
 * @copyright   Copyright 2016 meelier.com
 */
class BossmanageController extends BaseController
{	
	//public $layout = '/agent';
    public function actionIndex()
    {
        $this->redirect(Url::toRoute("bossmanage/list"));
    }  
    /**
     * 店面列表
     * @date: 2016-2-1 
     * @author: futao
     */
    public function actionList()
    {
		$account = $this->request->get("account",'');
		$bossName = $this->request->get("boss_name",'');
		$shopName = $this->request->get("shop_name",'');
		$phone = $this->request->get("phone",'');
		$state = $this->request->get("state",'');
		if($account!=''){
			$where[] = 'login_name like "%'.$account.'%"';
		}
		if($bossName!=''){
			$where[] = 'user_name like "%'.$bossName.'%"';
		}
		if($shopName!=''){
			$where[] = 'shop_name like "%'.$shopName.'%"';
		}
		if($phone!=''){
			$where[] = 'contact_mobile like "%'.$phone.'%"';
		}
		if($state==1){
			$where[] = 'sys_user.status = 1';
		}
		if($state==2){
			$where[] = 'sys_user.status != 1';
		}
		$where[] = "sys_boss.agent_uid = ".$this->userInfo->uid;
		$where[] = 'user_type = 3';
		$whereStr = implode(" and ",$where);
    	$query = SysBoss::find()
    	->select(['sys_boss.*','sys_user.*','sys_shop.*'])
    	->where($whereStr)
    	->leftJoin('sys_user','boss_uid = uid')
		->leftJoin('sys_shop','sys_shop.boss_uid = sys_boss.boss_uid');
    	$countquery = clone $query;
    	$pages=new Pagination(['totalCount' => $countquery->count(),'pageSize' => $this->pageNavLimit]);
    	$model=$query
    	->offset($pages->offset)
    	->limit($pages->limit)
    	->orderby("sys_boss.boss_uid desc")
    	->asArray()->all();
    	foreach ($model as $k=>$v){
    		$model[$k]['agent_name'] = SysUser::find()->select(['user_name as agent_name'])->where('uid = '.$model[$k]['agent_uid'])->asArray()->one();
    	}
		$data['model'] = $model;
		$data['page'] = $pages;
		$data['account'] = $account;
		$data['bossName'] = $bossName;
		$data['shopName'] = $shopName;
		$data['phone'] = $phone;
		$data['state'] = $state;
    	return $this->render('list',$data);
    }
    /**
     * 添加店面
     * @date: 2016-2-2 
     * @author: futao
     */
    public function actionAdd()
    {
    	if(!$this->request->isPost){
    		/* if($this->userInfo->user_type == 1){//系统管理员
    			$agentList = SysUser::find()->where("user_type = 2")->all();
    		}elseif($this->userInfo->user_type == 2){//代理商
    			$agentList[] = $this->userInfo;
    		} */
    		$agentList[] = $this->userInfo;
    		return $this->render('add',['agent_list'=>$agentList]);
    	}
    	$user_name = $this->request->post("user_name",'');
    	$user_pass = $this->request->post("user_pass",'');
    	$boss_name = $this->request->post("boss_name",'');
    	$shop_name = $this->request->post("shop_name",'');
    	$agent_id = $this->request->post("agent_id",'');
    	$phone = $this->request->post('phone','');
    	$info=SysUser::find()->where("login_name = '".$user_name."'")->one();
    	if($info){
    		$this->error("账号已注册！");
    	}
    	if(empty($user_name) || empty($user_pass) || empty($boss_name) || empty($agent_id) || empty($phone)){
    		$this->error("参数不完整！");
    	}
    	//判断代理商的点数是否够用
    	$agent = SysAgent::findOne($agent_id);
    	if($agent->point <= 0){
    	    $this->error("你的点数已用完！");
    	}
    	$transaction = Yii::$app->db->beginTransaction();
    	try{
	    	$userModel = new SysUser();
	    	$userModel->login_name = $user_name;
	    	$userModel->password = $this->strEncryption($user_pass);
	    	$userModel->user_type = 3;
	    	$userModel->create_uid = $this->userInfo->uid;
	    	$userModel->create_name = $this->userInfo->user_name;
	    	$userModel->mobile = $phone;
	    	$userModel->user_role = 3;
	    	$userModel->user_name = $boss_name;
	    	$userModel->save(false);
	    	$agentInfo = SysUser::findone($agent_id);
			$bossModel = new SysBoss();
			$bossModel->boss_uid = $userModel->uid;
	    	$bossModel->agent_uid = $agent_id;
	    	$bossModel->agent_login_name = $agentInfo->login_name;
	    	$bossModel->online_count = 0;
	    	$bossModel->contact_mobile = $phone;
	    	$bossModel->shop_count = 1;
	    	$bossModel->save(false);
	    	$shopModel = new SysShop();
	    	$shopModel->shop_uid = '';
	    	$shopModel->shop_name = $shop_name;
	    	$shopModel->status = 1;
	    	$shopModel->boss_uid = $bossModel->boss_uid;
	    	$shopModel->boss_login_name = $bossModel->agent_login_name;
	    	$shopModel->agent_uid = $agent_id;
	    	$shopModel->agent_login_name = $agentInfo->login_name;
	    	$shopModel->isopen_online = 2;
	    	//默认开通时间为1年
	    	$shopModel->start_time = date('Y-m-d H:i:s');
	    	$shopModel->end_time = date('Y-m-d H:i:s', strtotime("+1 year"));
	    	$shopModel->save(false);
	    	//申请开通线上店铺
	    	$result = $this->applyOnline($shopModel->shop_id);
	    	if(!$result){
	    	    $this->error("申请失败！");
	    	}
	    	//修改代理商点数(默认扣一点)
	    	$agent->point = $agent->point - 1;
	    	$agent->save(false);
	    	$transaction->commit();
    	}catch(\Exception $e){
    		$transaction->rollback();
    		$this->error("添加失败！");
    	}
    	$this->redirect(Url::toRoute("bossmanage/list"));
    } 
    /**
     * 编辑店面
     * @date: 2016-2-4
     * @author: futao
     */
    public function actionEdit()
    {
    	if(!$this->request->isPost){
    		$id = $this->request->get("id",0);
    		if($id<1){
    			$this->error("数据不存在！");
    		}
    		$bossInfo=SysBoss::find()
    		->select([
				'sys_user.login_name',
    			'sys_user.user_name',
    			'sys_boss.*'
    		])
    		->leftJoin("sys_user",'boss_uid = uid')
    		->where("boss_uid = :id and agent_uid = :uid and status = ".Status::NORMAL,[':id'=>$id,':uid'=>$this->userInfo->uid])->asArray()->one();
    		if(!$bossInfo){
    			$this->error("数据不存在！");
    		}
    		$shopList = SysShop::find()
    		->where("boss_uid = {$id} and status = 1")
    		->asArray()
    		->all();
    		return $this->render('edit',['bossInfo'=>$bossInfo,'id'=>$id,'shopList'=>$shopList]);
    	}
    	$bossName = $this->request->post('boss_name','');
    	$phone = $this->request->post('phone','');
    	$userPass = $this->request->post('user_pass','');
    	$id = intval($this->request->post('id',0));
    	if($id<1){
    		$this->error("数据错误！");
    	}
    	if(empty($bossName) || empty($phone)){
    		$this->error("数据不完整！");
    	}
    	$transaction = Yii::$app->db->beginTransaction();
    	try {
	    	$bossModel = SysBoss::find()
	    	->select("sys_boss.*")
	    	->leftJoin("sys_user",'boss_uid = uid')
	    	->where("boss_uid = :id and agent_uid = :uid and status = ".Status::NORMAL,[':id'=>$id,':uid'=>$this->userInfo->uid])
	    	->one();
	    	$bossModel->contact_mobile = $phone;
	    	$bossModel->save(false);
	    	$userModel = SysUser::find()->where("uid = :id and status = ".Status::NORMAL,[':id'=>$id])->one();
	    	$userModel->user_name = $bossName;
	    	if($userPass!=''){
	    		$userModel->password = $this->strEncryption($userPass);
	    	}
	    	$userModel->save(false);
	    	$transaction->commit();
    	}catch (\Exception $e){
    		$transaction->rollback();
    		$this->error("修改失败！");
    	}
    	$this->redirect(Url::toRoute(["bossmanage/edit",'id'=>$id]));
    }
    /**
     * 禁用账户
     * @date: 2016-2-15 
     * @author: futao
     */
    public function actionDisable(){
    	$id = intval($this->request->get('id',0));
    	if($id<0){
    		$this->error('参数错误！');
    	}
    	$bossModel = SysBoss::find()->where('boss_uid = :uid and agent_uid = :agent_uid',[':uid'=>$id,':agent_uid'=>$this->userInfo->uid])->one();
    	if(!$bossModel){
    		$this->error('操作失败！');
    	}
    	$userModel = SysUser::findOne($id);
    	$userModel->status = 0;
    	if(!$userModel->save(false)){
    		$this->error('操作失败！');
    	}
    	$this->redirect(Url::toRoute("bossmanage/list"));
    }
    /**
     * 启用账户
     * @date: 2016-2-15 
     * @author: futao
     */
    public function actionEnabled(){
    	$id = intval($this->request->get('id',0));
    	if($id<0){
    		$this->error('参数错误！');
    	}
    	$bossModel = SysBoss::find()->where('boss_uid = :uid and agent_uid = :agent_uid',[':uid'=>$id,':agent_uid'=>$this->userInfo->uid])->one();
    	if(!$bossModel){
    		$this->error('操作失败！');
    	}
    	$userModel = SysUser::findOne($id);
    	$userModel->status = 1;
    	if(!$userModel->save(false)){
    		$this->error('操作失败！');
    	}
    	$this->redirect(Url::toRoute("bossmanage/list"));
    }
    /**
     * 申请开通线上店铺
     * @date: 2016年3月16日 
     * @author: chenxiaolin
     */
    public function actionOpenonline(){
        //获取店铺Id
        $shop_id = intval($this->request->get('shop_id',0));
        if($shop_id < 1){
            $this->error('参数错误！');
        }
        $shop = SysShop::findOne($shop_id);
        if(empty($shop)){
            $this->error('店铺不存在！');
        }
        if($shop['isopen_online'] == 2){
            $this->error('你的申请已提交，正在审核中！');
        }
        if($shop['isopen_online'] == 1){
            $this->error('线上店铺已开通！');
        }
        $agent_uid = $shop['agent_uid'];
        $agent = SysAgent::findOne($agent_uid);
        if($agent['point'] <= 0){
            $this->error('你的点数已用完！');
        }
        $transAction = \Yii::$app->db->beginTransaction();
        try {
            //申请开通线上店铺（默认1年）
            $shop->start_time = date('Y-m-d H:i:s');
	    	$shop->end_time = date('Y-m-d H:i:s', strtotime("+1 year"));
	    	$shop->isopen_online = 2;
	    	$shop->save(false);
	    	$rs = $this->applyOnline($shop['shop_id']);
	    	if(!$rs){
	    	    $this->error("申请失败！");
	    	}
	    	//修改代理商点数(默认扣一点)
	    	$agent->point = $agent->point - 1;
	    	$agent->save(false);
            $transAction->commit();
        } catch (\Exception $e) {
            $transAction->rollback();
            $this->error("申请失败！");
        }
        $this->redirect(Url::toRoute(['bossmanage/edit','id' => $shop['boss_uid']]));
    }
    /**
     * 申请开通线上店铺(调用接口)
     * @date: 2016年3月16日 
     * @author: chenxiaolin
     */
    private function applyOnline($shop_id){
        $shop = SysShop::find()
        ->select(['sys_shop.*', 'sys_agent.*'])
        ->where("sys_shop.shop_id = :id", [':id' => $shop_id])
        ->leftJoin('sys_agent', 'sys_shop.agent_uid = sys_agent.agent_uid')->asArray()->all();
        $agent = SysUser::find()->where('uid = :uid',[':uid' => $shop[0]['agent_uid']])->one();
        $boss = SysUser::find()->where('uid = :uid',[':uid' => $shop[0]['boss_uid']])->one();
        $model = new OpenapiShop();
        $data = json_encode(array(
            'shop_name' => $shop[0]['shop_name'],
            'shop_id' => $shop[0]['shop_id'],
            'shop_uid' => $shop[0]['shop_uid'],
            'agent_id' => $shop[0]['agent_uid'],
            'agent_name' => $agent->user_name,
            'boss_mobile' => $boss->login_name,
            'start_time' => $shop[0]['start_time'],
            'end_time' => $shop[0]['end_time'],
            'longtime' => 1)
        );
        $baseUrl = \Yii::$app->params['baseUrl'];
        $url = \Yii::$app->params['apply'];
        // 发送请求获取数据
        try {
            $return = $model->get_url_msg($data, $baseUrl.$url);
            $return_info = json_decode($return, true);
            if ($return_info['status'] == 10000) {
                return true;
            } else {
                return false;
            }
            
        } catch (\Exception $e) {
            $this->error('访问网络出错！');
        }
    }
}
